package com.sunny.ihealth;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.WindowManager;

public class SplashActivity extends BaseActivity {

    public static final String SP_FILE_NAME = "user_data";
    public static final String SP_MODE = "mode";
    public static final String SP_USERNAME = "username";
    public static final String SP_PASSWORD = "password";

    public static final int MODE_FIRST_USE = 0;
    public static final int MODE_VISITOR = 1;
    public static final int MODE_REGISTER_USER = 2;

    private static final int SPLASH_TIME = 2 * 1000;

    private int mode;
    private String username;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);

        new Thread(new Runnable() {
            @Override
            public void run() {
                long time = System.currentTimeMillis();
                initUserState();
                time = SPLASH_TIME - (System.currentTimeMillis() - time);
                if (time > 0) {
                    try {
                        Thread.sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


                Intent intent = new Intent();
                intent.putExtra(SP_MODE, mode);
                if (mode == MODE_FIRST_USE) {
                    intent.setClass(SplashActivity.this, VisitorActivity.class);
                } else {
                    if (mode == MODE_REGISTER_USER) {
                        intent.putExtra(SP_USERNAME, username);
                        intent.putExtra(SP_PASSWORD, password);
                    }
                    intent.setClass(SplashActivity.this, MainActivity.class);
                }
                startActivity(intent);
                finish();
            }
        }).start();
    }


    /**
     * sp name:user_data
     * 使用模式mode
     * 账号username
     * 密码password
     */
    private void initUserState() {
        SharedPreferences sp = getSharedPreferences(SP_FILE_NAME, MODE_PRIVATE);
        mode = sp.getInt(SP_MODE, MODE_FIRST_USE);
        if (mode == MODE_REGISTER_USER) {
            username = sp.getString(SP_USERNAME, null);
            password = sp.getString(SP_PASSWORD, null);
            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                mode = MODE_VISITOR;
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
